﻿using AntdUI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace AntdUILogger
{
    public partial class Form1: Window
    {
		StringBuilder sbApendLog = new StringBuilder(128 * 1024);
		DateTime start = DateTime.Now;

		public Form1()
        {
            InitializeComponent();

			
            AntdUI.ITask.Run(() =>
            {
				int i = 0;
                while (true)
                {
					Thread.Sleep(1);
					String msg = $"this is long text log line for test input control, the log id = {i++}, means add {i} times\n";

					String text = null;

					lock (sbApendLog)
					{
						if (sbApendLog.Length + msg.Length > sbApendLog.Capacity)
						{
							text = sbApendLog.ToString();
							sbApendLog.Clear();
						}
						sbApendLog.Append(msg);
					}
					if (!String.IsNullOrEmpty(text))
					{
						UpdateLog(text);
					}
				}
			});
        }

		#region 定时刷log

		private void UpdateLog(String log)
		{
			Invoke(() =>
			{
				DateTime now = DateTime.Now;

				long interval = (long)(now - start).TotalMilliseconds;
				start = now;


				if (inputLogger.Text.Length + log.Length >= inputLogger.MaxLength)
				{
					if (log.Length >= inputLogger.MaxLength)
					{
						inputLogger.Text = log.Substring(log.Length - inputLogger.MaxLength);
					}
					else
					{
						inputLogger.Text = inputLogger.Text.Remove(0, inputLogger.Text.Length + log.Length - inputLogger.MaxLength + 100000);

						inputLogger.AppendText(log);
					}
				}
				else
				{
					inputLogger.AppendText(log);
				}

				inputLogger.SelectionStart = inputLogger.Text.Length;
				inputLogger.ScrollToCaret();
				inputLogger.ClearUndo();
				now = DateTime.Now;

				long spend = (long)(now - start).TotalMilliseconds;
				Console.WriteLine($"Update interval :{interval}, spend:{spend}");

			});

		}


		private void timer_Tick(object sender, EventArgs e)
		{
			lock (sbApendLog)
			{
				if (sbApendLog.Length > 0)
				{
					UpdateLog(sbApendLog.ToString());
					sbApendLog.Clear();
				}
			}
		}
		#endregion
	}
}
